﻿#region License
// (c) Intergen.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.
#endregion

using System;
using System.Globalization;

namespace MediaWiki.Office.Model
{
  public struct DocumentColor
  {
    private readonly bool _auto;
    private readonly byte _r;
    private readonly byte _g;
    private readonly byte _b;

    public bool Auto
    {
      get { return _auto; }
    }

    public byte R
    {
      get { return _r; }
    }

    public byte G
    {
      get { return _g; }
    }

    public byte B
    {
      get { return _b; }
    } 

    public DocumentColor(bool auto)
    {
      _auto = auto;
      _r = 0;
      _g = 0;
      _b = 0;
    }

    public DocumentColor(byte r, byte g, byte b)
    {
      _auto = false;
      _r = r;
      _g = g;
      _b = b;
    }

    public static DocumentColor? Parse(string colorText)
    {
      if (colorText == null)
        return null;

      if (colorText.Length == 0)
        throw new ArgumentException("Color text empty.");

      if (string.Compare(colorText, "auto", StringComparison.OrdinalIgnoreCase) == 0)
        return new DocumentColor(true);

      byte r = (byte)int.Parse(colorText.Substring(0, 2), NumberStyles.HexNumber);
      byte g = (byte)int.Parse(colorText.Substring(2, 2), NumberStyles.HexNumber);
      byte b = (byte)int.Parse(colorText.Substring(4, 2), NumberStyles.HexNumber);

      return new DocumentColor(r, g, b);
    }

    public override string ToString()
    {
      if (_auto)
        return "Auto";

      return string.Format("{{r:{0},g:{1},b:{2}}}", _r, _g, _b);
    }
  }
}